package org.joy.db2.query;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.List;

import org.joy.db2.Env;
import org.joy.db2.QueryServer;
import org.joy.db2.ResultEntry;

public class SocketServer {
    private DatagramSocket s;

    public SocketServer() throws IOException {
	QueryServer qs = new QueryServer();
	s = new DatagramSocket(1987);
	System.out.println("Listening from 1987...");
	while (true) {
	    // read query
	    DatagramPacket p = new DatagramPacket(new byte[4096], 4096);
	    s.receive(p);
	    byte[] data = new byte[p.getLength()];
	    System.arraycopy(p.getData(), p.getOffset(), data, 0, data.length);
	    BufferedReader br = new BufferedReader(new InputStreamReader(
		    new ByteArrayInputStream(data),"utf-8"));
	    String line = br.readLine();

	    s.connect(p.getSocketAddress());
	    // parse the query, and return the result
	    if (line.startsWith("s ")) {
		int count = Integer.parseInt(line.split(" ")[1]);
		int[] terms = new int[line.split(" ").length - 2];
		for (int i = 2; i < line.split(" ").length; i++) {
		    terms[i - 2] = line.split(" ")[i].hashCode();
		}
		List<ResultEntry> res = qs.search(terms, count);
		// return the result, one per line.
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
			baos,"utf-8"));
		for (ResultEntry i : res) {
		    bw.write(i.toString() + "\n");
		}
		bw.close();
		s.send(new DatagramPacket(baos.toByteArray(), baos.size()));
		s.disconnect();
	    }

	}
    }

    public static void main(String[] args) throws IOException,
	    InstantiationException, IllegalAccessException,
	    ClassNotFoundException {
	String dbFolder = args.length >= 1 ? args[0] : "/db";
	Env.setFolder(dbFolder);
	// String spliterName = args.length >= 2 ? args[1]
	// : "org.joy.nlp.ACWordSpliter";
	// QueryServer.setSpliter((WordSpliter)
	// Class.forName(spliterName).newInstance());
	new SocketServer();
    }
}
